package com.tanhua.admin.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.admin.enums.AreaEnum;
import com.tanhua.admin.pojo.*;
import com.tanhua.admin.vo.*;
import com.tanhua.admin.mapper.LoggingMapper;
import com.tanhua.dubbo.server.api.QuanZiApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: JinboYang
 * @Description:
 * @Date: Created in 下午 13:56 2021/1/17
 * @ModifiedBy:
 */
@Service
public class DashBoardService {


    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private LoggingMapper loggingMapper;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    /**
     * @Description: 新增、活跃用户、次日留存率
     * @Param:[sd, ed, type]
     * @return:void
     * @Author:JinboYang
     * @Date:2021/1/17
     */
    public DashBoardVo dashBoardMsg(Long sd, Long ed, Integer type) {
        DashBoardVo dashBoardVo = new DashBoardVo();
        List<YearData> thisYearList = new ArrayList<>();
        List<YearData> lastYearList = new ArrayList<>();

        //将区域分成12个部分
        Long avg = (ed - sd) / 12;
        List<Long> thisYearTimeList = new ArrayList<>();
        List<Long> lastYearTimeList = new ArrayList<>();

        Long lastYearSd = DateUtils.addYears(new Date(sd), -1).getTime();
        for (int i = 0; i <= 12; i++) {
            thisYearTimeList.add(sd + avg * i);
            lastYearTimeList.add(lastYearSd + avg * i);
        }

        //设置一段时间内的用户数
        List<Integer> counts = null;

        //设置类型
        switch (type) {
            //新增
            case 101: {
                counts = this.userService.saveUser(thisYearTimeList, lastYearTimeList);
                break;
            }
            //活跃用户
            case 102: {
                counts = this.quanZiApi.queryCommentCounts(thisYearTimeList, lastYearTimeList);
                break;
            }
            //次日留存率
            case 103: {
                List<List<Long>> nextList = this.userService.queryNextDay(thisYearTimeList, lastYearTimeList);
                counts = this.quanZiApi.queryNextDay(nextList, thisYearTimeList, lastYearTimeList);
                break;
            }
            default:{
                break;
            }
        }

        if (CollectionUtils.isEmpty(counts)) {
            return null;
        }

        //设置每个时间段的新增用户
        for (int i = 1; i <= counts.size(); i++) {
            YearData yearData = new YearData();
            yearData.setAmount(counts.get(i-1));
            //判断是今年的还是去年的 奇数是今年的 偶数是去年的
            if (i % 2 == 1) {
                yearData.setTitle(String.valueOf((i + 1) / 2));
                thisYearList.add(yearData);
            } else {
                yearData.setTitle(String.valueOf(i / 2));
                lastYearList.add(yearData);
            }

        }
        dashBoardVo.setThisYear(thisYearList);
        dashBoardVo.setLastYear(lastYearList);

        return dashBoardVo;
    }


    /**
     * @Description: 总计概述
     * @Param:[]
     * @return:java.util.Map<java.lang.String,java.lang.Object>
     * @Author:JinboYang
     * @Date:2021/1/18
     */

    public SummaryVo querySummaryData() {
        SummaryVo summaryVo = new SummaryVo();
        // 累计用户
        summaryVo.setCumulativeUsers(this.userService.queryCumulativeUsers());
        // 过去30天活跃用户
        DateTime nowTime =new DateTime();
        DateTime zeroTime = DateUtil.beginOfDay(nowTime);
        DateTime oldDate = DateUtil.offsetDay(zeroTime, -30);
        summaryVo.setActivePassMonth(this.quanZiApi.queryActivePassMonth(oldDate, zeroTime));
        // 过去7天活跃用户
        DateTime sevenDate = DateUtil.offsetDay(zeroTime, -7);
        summaryVo.setActivePassWeek(this.quanZiApi.queryActiveSevenDays(sevenDate, zeroTime));
        // 今日新增用户
        Integer todayNewUser = this.userService.queryUsersByTime(zeroTime, nowTime);
        summaryVo.setNewUsersToday(todayNewUser);
        // 今日新增用户涨跌率，单位百分数，正数为涨，负数为跌
        DateTime yesterdayTime = DateUtil.offsetDay(zeroTime, -1);
        summaryVo.setNewUsersTodayRate(this.userService.queryUsersByTime(yesterdayTime, zeroTime) - todayNewUser);
        // 今日登录次数
        Integer todayLoginCount = this.quanZiApi.queryLoginCountByTime(zeroTime, nowTime);
        summaryVo.setLoginTimesToday(todayLoginCount);
        // 今日登录次数涨跌率，单位百分数，正数为涨，负数为跌
        summaryVo.setLoginTimesTodayRate(this.quanZiApi.queryLoginCountByTime(yesterdayTime, zeroTime) - todayLoginCount);
        // 今日活跃用户
        Integer todayActive = this.quanZiApi.queryActiveUserByTime(zeroTime, nowTime);
        summaryVo.setActiveUsersToday(todayActive);
        // 今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        Integer yesterdayActive = this.quanZiApi.queryActiveUserByTime(yesterdayTime, zeroTime);
        summaryVo.setActiveUsersTodayRate(yesterdayActive - todayActive);
        // 过去7天平均日使用时长，单位秒
        summaryVo.setUseTimePassWeek(12561); //
        //  昨日活跃用户
        summaryVo.setActiveUsersYesterday(yesterdayActive);
        //   昨日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        DateTime beforeYesterday = DateUtil.offsetDay(yesterdayTime, -1);
        summaryVo.setActiveUsersYesterdayRate(this.quanZiApi.queryActiveUserByTime(beforeYesterday, yesterdayTime) - yesterdayActive);

        return summaryVo;
    }

    /**
       * @Description: 注册用户分布，行业top、年龄、性别、地区
       * @Param:[sd, ed]
       * @return:com.tanhua.admin.vo.DistributionVo
       * @Author:JinboYang
       * @Date:2021/1/18
       */
    public DistributionVo queryDistributionData(Long sd, Long ed) {

        DistributionVo distributionVo = new DistributionVo();
        // 根据创建时间去查所有的用户
        List<User> userList = this.userService.queryUserListByTime(sd, ed);

        // 取出用户id
        List<Long> userIds = new ArrayList<>();
        for (User user : userList) {
            userIds.add(user.getId());
        }
        if (CollectionUtils.isEmpty(userIds)) {
            return distributionVo;
        }

        List<Map<String, Object>> cityList = this.userInfoService.queryCityList(userIds);
        List<Map<String, Object>> industryList = this.userInfoService.queryIndustryList(userIds);
        List<Map<String, Object>> ageList = this.userInfoService.queryAgeList(userIds);
        List<Map<String, Object>> genderList = this.userInfoService.queryGenderList(userIds);

        distributionVo.setAgeDistribution(this.getList(ageList));
        distributionVo.setGenderDistribution(this.getList(genderList));
        distributionVo.setIndustryDistribution(this.getList(industryList));
        distributionVo.setLocalDistribution(this.getProvinceList(cityList));

        distributionVo.setLocalTotal(this.getLocalCounts(cityList));

        return distributionVo;
    }

    /**
       * @Description: 获取地区总数
       * @Param:[map]
       * @return:java.util.List<com.tanhua.admin.pojo.YearData>
       * @Author:JinboYang
       * @Date:2021/1/18
       */
    private List<YearData> getLocalCounts(List<Map<String, Object>> map) {
        Map<String, Long> countMap = new HashMap<>();

        for (Map<String, Object> integerMap : map) {
            String province = StringUtils.substring(integerMap.get("title").toString(), 0, 2);
            String key = AreaEnum.getAreaByProvince(province);
            if (countMap.containsKey(key)) {
                countMap.put(key, Long.parseLong(integerMap.get("amount").toString()) + countMap.get(key));
            } else {
                countMap.put(key, Long.parseLong(integerMap.get("amount").toString()));
            }
        }

        List<YearData> list = new ArrayList<>();
        for (String s : countMap.keySet()) {
            list.add(new YearData(s, countMap.get(s).intValue()));
        }

        return list;
    }

    /**
       * @Description: 获取省份列表
       * @Param:[map]
       * @return:java.util.List<com.tanhua.admin.pojo.YearData>
       * @Author:JinboYang
       * @Date:2021/1/18
       */
    private List<YearData> getProvinceList(List<Map<String, Object>> map) {
        List<YearData> list = new ArrayList<>();
        for (Map<String, Object> integerMap : map) {
            list.add(new YearData(integerMap.get("title").toString().substring(0, 2), Integer.parseInt(integerMap.get("amount").toString())));
        }
        return list;
    }


    private List<YearData> getList(List<Map<String, Object>> map) {
        List<YearData> list = new ArrayList<>();
        for (Map<String, Object> integerMap : map) {
            list.add(new YearData(integerMap.get("title").toString(), Integer.parseInt(integerMap.get("amount").toString())));
        }
        return list;
    }
}
